<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\25 0025
 * Time: 9:53
 */

namespace app\Lib\Model\SysConfig\SysConfigManage;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\User\UserHandle;
use app\Lib\Model\DbModel\AdminConfig;
use app\Lib\Model\SysConfig\SysConfig;

class DelConfig implements \app\Lib\InterfaceIn\SysConfig\SysConfigManage\DelConfig
{
    private $id;
    private $opUser;
    private $table;
    /**
     * 初始化
     * DelConfig constructor.
     * @param $id
     * @param UserHandle $opUser
     */
    public function __construct($id, UserHandle $opUser)
    {
        $this->id = $id;
        $this->opUser = $opUser;
    }

    /**
     * 真正执行
     * @return bool
     * @throws BlException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function run()
    {
        $this->validate();
        $model  =  $this->getTable();
        $data   = [
            $model->_id=>$this->id,
            $model->_status=>0,
        ];
        $result = $model->update($data);
        if(!$result){
            throw new BlException('禁用失败');
        }
        return true;
    }

    private function getTable(){
        if(empty($this->table)){
            $this->table = new AdminConfig();
        }
        return $this->table;
    }

    /**
     *
     * @return bool
     * @throws BlException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function validate(){
        $model = $this->getTable();
        $info  = $model->where($model->_id,$this->id)->field([$model->_id,$model->_status,$model->_variable])->find();
        if(empty($info)){
            throw new BlException('获取修改信息失败_empty');
        }
        if($info['status'] == 0){
            throw new BlException('该条数据已禁用');
        }
        /*删除缓存*/
        SysConfig::delValue($info['variable']);
        return true;
    }

}